
#include "kb.h"                 // keybaord event type 
#include "touch_algorithm.h"    // touch event type 
#include "custom_event.h"
#include "gui.h"                // GUI header

#include "views.h"              // include all views 
#include "log.h"                // LOG file 

#define LOG     LOG_INFO0
#define LOG1    LOG_INFO1

#include "xapp_clock.h"
#include "xapp_qrcode.h"
#include "xapp_localize.h"
#include "xapp_system.h"

enum tagQrcodeDevApp
{
    tagQrcodeDevAppBack,
    tagQrcodeDevAppTryToEnterFactoryTest,
};

// declare function 
GUI_VIEW_FUNC_DECLARE_ALL;
static void local_view_event_handler( uint32_t tag );

static uint8_t* mp_qrcode_matrix;


const static ui_widgets_type_t wglApplink/*1. modify name*/[] = 
{
    // set background black 
    [0] = uiCanvas(0, 0, GUI_LCD_RES_H, GUI_LCD_RES_V, COLOR_BLACK ),

    [1] = uiTextScroll( SIZE_SCALE(52), SIZE_SCALE(20), SIZE_SCALE(120), SIZE_SCALE(29), COLOR_BLACK, COLOR_WHITE, ALIGN_LEFT_TOP, FILL_NONE, ENCODING_UNICODE, FONT_UNICODE_20_29  ),

    // QRCODE
    [2] = uiQrcode( SIZE_SCALE(30), SIZE_SCALE(40), SIZE_SCALE(180), SIZE_SCALE(180), COLOR_BLACK, COLOR_WHITE, NULL ),
};

static const ui_widgets_type_t uiTouchList[] = 
{
    [0] = uiTouch( 0, 0, GUI_LCD_RES_H, SIZE_SCALE(80/*50*/), tagQrcodeDevAppTryToEnterFactoryTest ),
};

static const ui_refresh_part_t wglApplinkPart[] = 
{
    [0] = xRECTANGLE( SIZE_SCALE(52), SIZE_SCALE(20), SIZE_SCALE(120), SIZE_SCALE(29) ),
};

GUI_VIEW_DEF( viewDevInfo_AppLink ) =
{
    // name 
    .name = "DevInfo+AppLink",
    
    // init 
    .init = initialize,
    .display_func = display_callback_func,
    .refresh_func_check = display_refresh_func,
    .destroy_func = on_destroy_func,
    .set_parent_func = on_set_parent_func, 
    
    // input 
    .on_touch = on_touch,
    .on_button = on_button,
    .on_event_update = on_event_update,  

    .pWidgetlist =  (ui_widgets_type_t*)wglApplink /* 3. fill with widgets list name */,
    .widget_cnt = WIDGET_COUNT( wglApplink ), /* 3. fill with widgets list name */

    .flag = GUI_VIEW_FLAG_FUNC | GUI_VIEW_FLAG_ALIVE_DELAY
};

static uint32_t timestamp_click ;
static uint8_t enter_factory_test_count;


/* 当前view初始化
// 需要指定前使用的控件组
// 自动更新间隔，不使用自动更新间隔则interval = 0

*/
static void initialize(gui_menu_t * menu, void* pvParameter)
{
    menu->interval = 0;
    menu->lifetime = 60000; 

    mp_qrcode_matrix = xapp_qrcode_get_applink_devinfo(  );
    enter_factory_test_count = 0;
}

static void on_set_parent_func(gui_menu_t * menu, const gui_view_t * parent)
{
    p_this_parent = parent;
}
/* 销毁函数
// 在销毁前处理当前信息，比如不允许销毁时，将当前界面状态保存为background。
// true:  允许销毁
// false: 不允许自动销毁，则GUI只关闭当前显示，输入事件仍由当前view进行处理。
          那么view判断当前状态为background时，作出对应background下的按键、触摸等事件反馈
*/
static uint32_t on_destroy_func(gui_menu_t * menu)
{    
    xapp_qrcode_free_buffer( );
    return GUI_DESTROY_RET_DEFAULT; 
}


/* 显示回调
   重新指定参数, 用来获取当前界面的控件组
   ** 当前界面有多个控件组时，应该有条件确定使用哪一组控件组 ** 
*/
static void display_callback_func(gui_menu_t * menu)
{
    ui_property_t prop;
    ui_widgets_type_t * widgets = menu->widgets;
   
    if( IS_REQ_SRC_CREATE( menu->source ) )
    {
        prop.qrcode.matrix = mp_qrcode_matrix;//(uint8_t*)xapp_qrcode_MAC_get_matrix();
        gui_widget_update_prop( &widgets[2], &prop );

        string_t const * s = xapp_local_text_item_get( TEXT_TAG_WATCH_QRCODE );
        PROP_ASSIGN_TEXTSCROLL_STRING( prop, s );
        PROP_UPDATE_AT_NO( 1 );
        
        if( IS_REQ_SRC_CREATE_SINGLE( menu->source ) )
        {
            gui_part_t part = GUI_PART_CONFIG(wglApplinkPart, 100);
            gui_part_create( &part );
        }
    }
    else if( menu->source == GUI_VIEW_REQ_SRC_UPDATE_PART )
    {
        PROP_ASSIGN_TEXTSCROLLED_ROLL( prop, -4 );
        PROP_UPDATE_AT_NO( 1 );
    }
}

/* 刷新显示回调
   根据当前状态，重新绘制指定的控件组 
*/
static int display_refresh_func(gui_menu_t * menu)
{
    return 1;
}

static void on_touch(void* pvParameters, gui_menu_t * menu)
{
    tp_algo_evt_t* touch = (tp_algo_evt_t*)pvParameters;

    switch( touch->type )
    {        
        case TP_ALGO_EVT_TYPE_CLICK: // 连接多次，进入工厂测试界面 
        if(VIEW_CHECK_TOUCH( uiTouchList, touch->x, touch->y, local_view_event_handler  ))
        {
            LOG_INFO0("enter factory in zone" );
        }
        else
        {
            LOG_INFO0("enter factory out zone" );
        }
        break;

        case TP_ALGO_EVT_TYPE_SLIDE_R: // 未配对时，出现此二维码，出现在常用界面
        if( p_this_parent != NULL )
        {
            gui_view_create( p_this_parent );
        }
        else 
        {
            gui_view_create( &viewAppsList ); 
        }
        break;

        case TP_ALGO_EVT_TYPE_SLIDE_L:
        
        break;
        
        default:
        break;
    }
}
/* 界面的按键处理

*/
static void on_button(void* pvParameters, gui_menu_t * menu)
{
    kb_evt_t* kb = (kb_evt_t*)pvParameters;

    switch( kb->type )
    {
        case KB_EVT_CLICK:
        local_view_event_handler( tagQrcodeDevAppBack );
        break;
    }
}

/* 界面的自定义输入事件处理

*/
static void on_event_update(void * pvParameters, gui_menu_t * menu)
{
    (void)pvParameters;    
}

static void local_view_event_handler( uint32_t tag )
{
    switch( tag )
    {
        case tagQrcodeDevAppTryToEnterFactoryTest: 
        {
            uint32_t ticks = em_rtc_get_second_ticks();
            if( ticks > 120 ) // 开机两分钟内才允许进入工厂测试 模式 
            {
                LOG_INFO0("enter factory count already timeout 120s" );
                break;
            }

            if( em_rtc_check_time_expired( timestamp_click, EM_RTC_TOTICKS(500) ) )
            {
                enter_factory_test_count = 1;
            }
            else 
            {
                enter_factory_test_count ++;
                
                if( enter_factory_test_count > 5 )
                {
                    xapp_system_set_mode( SYSTEM_MODE_FACTORY_TEST ); // 进入工厂测试模式 
                }
            }
            LOG_INFO1("enter factory count = %d", enter_factory_test_count );
            timestamp_click = em_rtc_get_ticks();
        }
        break;

        case tagQrcodeDevAppBack:
        if( p_this_parent != NULL )
        {
            gui_view_create_return( p_this_parent );
        }
        else 
        {
            gui_view_create_return( &viewAppsList ); 
        }
        break;
    }
}
